<!-- author: xuett -->
<!-- date: 2024-06-18 11:44:40 -->
<!-- description: 代码编辑器 -->
<template>
  <el-dialog v-model="dialogVisible" :title="title">
    <!-- @ready="handleReady"
      @focus="onFocus"
      @change="onChange" -->
    <codemirror ref="myCmGenerate" v-model="codeValue" :style="{ height: '500px', fontSize: '16px' }" :extensions="extensions"></codemirror>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCode"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { Codemirror } from "vue-codemirror";
import { vue } from "@codemirror/lang-vue";
import { oneDark } from "@codemirror/theme-one-dark";
import beautify from "js-beautify";

const $props = defineProps({
  title: {
    type: String,
    default: "代码编辑器"
  },
  code: {
    type: String,
    default: ""
  },
  dark: {
    //是否暗黑主题
    type: Boolean,
    default: true
  }
});
const $emit = defineEmits(["updateCode"]);

const codeValue = ref("");
const extensions = $props.dark ? [vue(), oneDark] : [vue()];

const dialogVisible = ref(false);
//显示
const showCode = () => {
  codeValue.value = beautify($props.code, { indent_size: 2 });
  dialogVisible.value = true;
};
//隐藏
const hideCode = () => {
  dialogVisible.value = false;
};

// const handleReady = (payload) => {
//   console.log("ready:", payload);
// };

// const onFocus = (viewUpdate) => {
//   console.log("focus:", viewUpdate);
// };
// const onChange = (value, viewUpdate) => {
//   console.log("change:", viewUpdate);
// };

//确定
const confirmCode = () => {
  hideCode();
  $emit("updateCode", codeValue.value);
};

defineExpose({ showCode, hideCode });
</script>
<style lang="scss" scoped>
:deep(.cm-editor) {
  width: 100%;
  border-radius: 4px;
  outline: none;
  border: 1px solid transparent;
  .cm-scroller {
    border-radius: 8px;
  }
}
</style>
